<?php


namespace app\api\controller;


use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use app\tickets\controller\Jsapi;
use think\Config;
use think\Controller;
use think\Db;
use think\Exception;
use think\Session;
use think\Validate;

class Order extends Controller
{

    /**
     * 获取我的电子票
     * @return false|string
     * @author zhixuedong
     * @date 2021/1/31/031
     */
    public function eticket(){
        $common = new Common();
        try{
            $common = new Common();
            $userid = $common->common();
            $page = empty($_POST['page']) ? 1 : $_POST['page'];
            $limit = empty($_POST['limit']) ? 10 : $_POST['limit'];
            $start = ($page - 1) * $limit;
            $where['a.fans_id'] = $userid;
            $list = Db::name("tickets_list")->alias("a")
                ->join("tickets_order_detail c","a.order_id = c.order_id")
                ->field("a.status,a.effective_time,a.end_time,a.signcode,a.status,a.degree,a.check_time,c.title,c.thumb,c.price")
                ->where($where)->order("a.id desc")->select();
            //->limit($start,$limit)

            $count = Db::name("tickets_list")->alias("a")
                ->join("tickets_order_detail c","a.order_id = c.order_id")
                    ->where($where)->limit($start,$limit)->count("*");
            $black['code'] = 0;
            $black['list'] = $list;
            $black['count'] = $count;
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }


    //获取电子票(弃用)
    public function eticket_out(){
        $common = new Common();
        try{
            $common = new Common();
            $userid = $common->common();
            $page = empty($_POST['page']) ? 1 : $_POST['page'];
            $limit = empty($_POST['limit']) ? 10 : $_POST['limit'];
            $start = ($page - 1) * $limit;
            $showdata = date("Y-m-d");
            $where['a.fans_id'] = $userid;
            $where['a.status'] = 2;
            $where['b.effective_time'] = ["elt",$showdata];
            $where['b.end_time'] = ["egt",$showdata];
            $where['b.degree'] = ['gt',0];
            $list = Db::name("tickets_order")->alias("a")
                ->join("tickets_order_detail b","a.id = b.order_id")->where($where)
                ->field("a.order_sn,b.title,b.thumb,b.price")->limit($start,$limit)->select();
            $count = Db::name("tickets_order")->alias("a")
                ->join("tickets_order_detail b","a.id = b.order_id")->where($where)->count("*");
            $black['code'] = 0;
            $black['list'] = $list;
            $black['count'] = $count;
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    //发送短信
    public function sms($code,$phone){

        $current_date = date("Y-m-d");;
        //记录当天发送的数量
        $detail = Db::name("sms")->where(['phone'=>$phone,'current_date'=>$current_date])->find();
//        if($detail['count']>1){
//            throw new Exception("超出当天可发送的数量");
//        }
        if(empty($detail)){
            $data['phone'] = $phone;
            $data['current_date'] = $current_date;
            $data['count'] = 1;
            Db::name("sms")->insert($data);
        }else{
            Db::name("sms")->where(['phone'=>$phone,'current_date'=>$current_date])->setInc("count",1);
        }


        $common = new Common();
        require_once ROOT_PATH."extend/sms/api_sdk//vendor/autoload.php";//引入PHPExcel加载文件
        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();
        //可选-启用https协议
        //$request->setProtocol("https");
        // 必填，设置短信接收号码
        $request->setPhoneNumbers($phone);
        // 必填，设置签名名称，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $request->setSignName("鲸探");
        // 必填，设置模板CODE，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $request->setTemplateCode("SMS_190283810");
        // 可选，设置模板参数, 假如模板中存在变量需要替换则为必填项
        $request->setTemplateParam(json_encode(array(  // 短信模板中字段的值
            "code"=>$code,
        ), JSON_UNESCAPED_UNICODE));
        // 可选，设置流水号
        $request->setOutId("yourOutId");
        // 选填，上行短信扩展码（扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段）
        $request->setSmsUpExtendCode("1234567");
        // 发起访问请求
        $acsResponse = $common->getAcsClient()->getAcsResponse($request);
        return $acsResponse;
    }

    //生成订单号
    public function generateNo(){
        $common = new Common();
        $current_date = date("Ymd");
        $thisWechat = Session::get("thisWechat");
        $where['uniacid'] = $thisWechat['id'];
        $where['currentDate'] = $current_date;
        $table = "tickets_order";
        $order_sn = $common->public_select($table,$where)->order("order_sn desc")->value('order_sn');
        if(empty($order_sn)){
            $order_sn = $current_date."00001";
        }else{
            $order_sn = $order_sn+1;
        }
        return $order_sn;
    }


    public function createTest($employeeNo,$faceUrl){
        //对比人脸
        $commonDevice = new Test();
        $token = $commonDevice->token();
        $personsCreate['employeeNo'] = $employeeNo;
//        $faceUrl = "https://tickets-1253901423.cos.ap-nanjing.myqcloud.com/platform1/2021-02-05/8a4beee283cb02bb69063f471d11bde3.jpg";
//        $faceUrl = "https://tickets-1253901423.cos.ap-nanjing.myqcloud.com/platform1/2021-02-24/cc64c23afb42aa48fe9c94546d055348.jpg";

        //查询人员是否存在
        $personFace = $commonDevice->personFace($personsCreate['employeeNo'],$token);
        if($personFace['code']!=200){
            $personsCreate['personName'] = "对比人脸";
            $startTime = date("Y-m-d\T00:00:01P",time());
            $endtTime = date("Y-m-d\T23:59:59P",time());
            $personsCreate['validBeginTime'] = $startTime;
            $personsCreate['validEndTime'] = $endtTime;
            $cardValue = $commonDevice->personsCreate($personsCreate,$token,1);

            if(!empty($faceUrl)){
                $personsCreate['faceImageBase64'] = $faceUrl;
                $cardValue = $commonDevice->personsUpdate($personsCreate,1);
            }
        }else{
            //更新
            $personsCreate['personName'] = "对比人脸";
            if(!empty($faceUrl)){
                $personsCreate['faceImageBase64'] = $faceUrl;
            }
            $startTime = date("Y-m-d\TH:i:sP",time());
            $endtTime = date("Y-m-d\T23:59:59P",time());
            $personsCreate['validBeginTime'] = $startTime;
            $personsCreate['validEndTime'] = $endtTime;
            $cardValue = $commonDevice->personsUpdate($personsCreate,1);
        }
        //$commonDevice->personsDelete($personsCreate['employeeNo'],$token);
    }

    /**
     * 购票操作
     * @return false|string
     * @author zhixuedong
     * @date 2021/1/21/021
     */
    public function createOrder(){
        Db::startTrans();
        try {
            $count = empty($_POST['count'])?1:$_POST['count'];
            $common = new Common();
            $userid = $common->common();

            $rule = [
                ["name", "require", "姓名不能为空"],
                ["mobile", "require", "手机号不能为空"],
            ];
            $validate = new Validate($rule);
            $data = $this->request->post();
            if (!$validate->check($data)) {
                throw new Exception($validate->getError());
            }

            $name = empty($_POST['name'])?'':$_POST['name'];
            $mobile = empty($_POST['mobile'])?'':$_POST['mobile'];
            $IDcard = empty($_POST['IDcard'])?'':$_POST['IDcard'];
            $faceUrl = empty($_POST['faceUrl'])?'':$_POST['faceUrl'];
            $remark = empty($_POST['remark'])?'':$_POST['remark'];

            //查询票种库存
            $where['id'] = $_POST['id'];
            $publicTable = "tickets_tickets";
            $newSql = $common->public_select($publicTable,$where);
            $product = $newSql->find();
            if(empty($product)){
                throw new Exception("商品信息有误");
            }
            if($product['inventory']<=0){
                throw new Exception("票已售完");
            }

            $crew[] = ['name'=>$name,'mobile'=>$mobile,'IDcard'=>$IDcard,'face'=>$faceUrl];
            if($product['type'] > 1){
                if($count>1){
                    throw new Exception("该票种一次只能购买一张");
                }
                if($IDcard==''){
                    throw new Exception("身份证号码不能为空");
                }
            }





            /*
            $crew = [];
            foreach ($name as $k=>$v){
                if(!empty($mobile[$k])){
                    if(!$common->isMobile($mobile[$k])){
                        throw new Exception("【".$v."】手机号码格式有误");
                    }
                }
                if(!empty($IDcard[$k])){
                    if(!$common->setCard($IDcard[$k])){
                        throw new Exception("【".$v."】身份证号码有误");
                    }
                }

                $face = '';
                $face = empty($face[$k])?'':$face[$k];
                $crew[$k] = ['name'=>$v,'mobile'=>$mobile[$k],'IDcard'=>$IDcard[$k],'face'=>$face];
            }*/
            $crew = json_encode($crew);

            $whereFans['id'] = $userid;
            $fansTable = "admin_fans";
            $fans = $common->public_select($fansTable,$whereFans)->find();

            //生成核销码
            $order_sn = $this->generateNo();

            //判断人脸是否合格
            $this->createTest($order_sn,$faceUrl);


            //生成订单
            $thisWechat = Session::get("thisWechat");
            $order['uniacid'] = $thisWechat['id'];
            $order['fans_id'] = $fans['id'];
            $order['pay_type'] = 1;
            $order['real_pay'] = $product['price']*$count;
            $order['total_amount'] = $product['price']*$count;
            $order['order_sn'] = $order_sn;
            $order['addtime'] = time();
            $order['currentDate'] = date("Ymd",time());
            $order['year'] = date("Y",time());
            $order['month'] = date("m",time());
            $order['name'] = $name;
            $order['mobile'] = $mobile;
            $order['IDcard'] = $IDcard;
            $order['crew'] = $crew;
            $orderTable = "tickets_order";
            $order_id = $common->handle($orderTable,$order);

            if(empty($fans['realName'])){
                $fansData['realName'] = $name;
                $fansData['idCard'] = $IDcard;
                $fansData['mobile'] = $mobile;
                if($faceUrl!='null'){
                    $fansData['faceUrl'] = $faceUrl;
                }
                //执行实名
                $common->public_select($fansTable,$whereFans)->update($fansData);
            }

            //插入票信息
            $order_product['order_id'] = $order_id;
            $order_product['tickets_id'] = $product['id'];
            $order_product['title'] = $product['title'];
            $order_product['thumb'] = $product['thumb'];
            $order_product['type'] = $product['type'];
            $order_product['validity'] = $product['validity'];
            $order_product['price'] = $product['price'];
            $order_product['time_range'] = $product['time_range'];
            $order_product['address'] = $product['address'];
            $order_product['content'] = $product['content'];
            $order_product['count'] = $count;
            $validity = $product['validity']-1;
            $order_product['effective_time'] = empty($_POST['effective_time'])?date("Y-m-d",time()):$_POST['effective_time'];
            $order_product['end_time'] = date("Y-m-d",strtotime("+".$validity." day",strtotime($order_product['effective_time'])));
            $order_product['degree'] = $product['degree'];
            $tickets_order_detail = "tickets_order_detail";
            $common->handle($tickets_order_detail,$order_product);
            //减库存
            $common->public_select($publicTable,$where)->setDec("inventory",intval($count));

            //生成订单操作流程
            $ordeLog['order_id'] = $order_id;
            $ordeLog['title'] = "订单提交成功 操作人:下单顾客";
            $ordeLog['remark'] = "核销码:".$order_sn;
            $ordeLog['addtime'] = time();
            $ordeLog['add_id'] = $userid;
            $system_order_log = "tickets_order_log";
            $common->handle($system_order_log,$ordeLog);

            //插入日志
            $realName = empty($fans['realName'])?$fans['nickname']:$fans['realName'];
            $log['remark'] = "市民【" . $realName  . "】购票，核销码【".$order_sn."】,关联id【".$order_id."】" ;
            $common->addLog($log);

            $black['code'] = 0;
            $black['msg'] = "操作成功";
            $black['order_id'] = $order_id;
            $black['order_sn'] = $order_sn;
            Db::commit();
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
            Db::rollback();
        }
        return json_encode($black);
    }

    /**
     * 提交订单操作
     * @return false|string
     * @author zhixuedong
     * @date 2021/1/21/021
     */
    public function updateOrder(){
        Db::startTrans();
        try{
            $common = new Common();
            $userid = $common->common();
            if(empty($_POST['order_id'])){
                throw new Exception("请选择要操作的订单");
            }
            if(empty($_POST['mobile'])){
                throw new Exception("请填写手机号码");
            }
            $order_id = $_POST['order_id'];
            $name = empty($_POST['name'])?'':$_POST['name'];
            $mobile = empty($_POST['mobile'])?'':$_POST['mobile'];
            $IDcard = empty($_POST['IDcard'])?'':$_POST['IDcard'];
            $remark = empty($_POST['remark'])?'':$_POST['remark'];

            if($mobile=='' && $IDcard==''){
                throw new Exception("请填写手机号码货身份证信息");
            }

            if(!empty($mobile)){
                if(!$common->isMobile($mobile)){
                    throw new Exception("手机号码格式有误");
                }
            }

            if(!empty($IDcard)){
                if(!$common->setCard($IDcard)){
                    throw new Exception("身份证号码有误");
                }
            }

            //更新订单购买信息
            $tickets_order = "tickets_order";
            $data['name'] = $name;
            $data['mobile'] = $mobile;
            $data['IDcard'] = $IDcard;
            $data['remark'] = $remark;
            $data['id'] = $order_id;
            $common->handle($tickets_order,$data);
            $black['code'] = 0;
            $black['msg'] = "操作成功";
            Db::commit();
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
            Db::rollback();
        }
        return json_encode($black);
    }


    /**
     * 更新数量
     * plus加  minus减
     * @author zhixuedong
     * @date 2021/1/21/021
     */
    public function updateCount(){
        Db::startTrans();
        try{
            $common = new Common();
            $userid = $common->common();
            $order_id = $_POST['order_id'];
            $operation = $_POST['operation'];
            $tickets_order = "tickets_order";
            $tickets_where['id'] = $order_id;
            $status = $common->public_select($tickets_order,$tickets_where)->value("status");
            if($status!=1){
                throw new Exception("非法操作");
            }

            $tickets_order_detail = "tickets_order_detail";
            $where['order_id'] = $order_id;
            $order_detail = $common->public_select($tickets_order_detail,$where)->find();

            //已购买票数 $order_detail['count'];
            if($order_detail['type']!=1){
                throw new Exception("该票种一次只能购买一张");
            }
            $tickets_tickets_where['id'] = $order_detail['tickets_id'];
            $tickets_tickets = "tickets_tickets";
            //查询库存是否充足
            $newSql = $common->public_select($tickets_tickets,$tickets_tickets_where);
            $product = $newSql->find();

            if($operation=="plus"){
                if($product['inventory']<=0){
                    throw new Exception("票已售完");
                }
                //减库存
                $common->public_select($tickets_tickets,$tickets_tickets_where)->setDec("inventory",1);
                //更新购买库存
                $common->public_select($tickets_order_detail,$where)->setInc("count",1);
                //更新订单金额
                $common->public_select($tickets_order,$tickets_where)->setInc("real_pay",$product['price']);
                $common->public_select($tickets_order,$tickets_where)->setInc("total_amount",$product['price']);

            }else{
                if($order_detail['count']==1){
                    throw new Exception("至少购买一张");
                }
                //加库存
                $common->public_select($tickets_tickets,$tickets_tickets_where)->setInc("inventory",1);
                //更新购买库存
                $common->public_select($tickets_order_detail,$where)->setDec("count",1);
                //更新订单金额
                $common->public_select($tickets_order,$tickets_where)->setDec("real_pay",$product['price']);
                $common->public_select($tickets_order,$tickets_where)->setDec("total_amount",$product['price']);
            }
            $black['code'] = 0;
            $black['msg'] = "操作成功";
            Db::commit();
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
            Db::rollback();
        }
        return json_encode($black);
    }

    /**
     * 支付操作
     * @return false|string
     * @author zhixuedong
     * @date 2021/1/21/021
     */
    public function payment(){

        Db::startTrans();
        try{
            $common = new Common();
            $userid = $common->common();


            $whereFans['id'] = $userid;
            $fansTable = "admin_fans";
            $fans = $common->public_select($fansTable,$whereFans)->find();


            $rule = [
                ["order_id", "require", "非法操作"],
                ["paytype", "require", "请选择支付方式"],
            ];
            $validate = new Validate($rule);
            $request = $this->request->post();
            if (!$validate->check($request)) {
                throw new Exception($validate->getError());
            }

            $order_id = $request['order_id'];
            $paytype = $request['paytype'];


            //获取订单金额
            $tickets_order = "tickets_order";
            $tickets_order_where['id'] = $order_id;
            $orderDetail = $common->public_select($tickets_order,$tickets_order_where)->find();
            //获取订单商品信息
            $tickets_order_detail = "tickets_order_detail";
            $tickets_order_detail_where['order_id'] = $order_id;
            $orderProduct = $common->public_select($tickets_order_detail,$tickets_order_detail_where)->find();

            if($orderDetail['is_pay']!=1){
                throw new Exception("该订单已付款,请勿重复操作");
            }
            if(empty($orderDetail)){
                throw new Exception("订单信息不存在");
            }
            $pay_time = time();
            switch ($paytype){
                case "1":  //微信支付
                    $appid = $request['appid'];
//                    nonceStr: 'A1B2C3D4E5',
//                    package: 'prepay_id=wx20180101abcdefg',
//                    signType: 'MD5',
//                    paySign: '',
                    $tools = new Jsapi();
                    $black['applet'] = $tools->appletPay($orderDetail['real_pay'],$fans['xcx_openid'],$orderDetail['id'],$orderDetail['order_sn'],$orderProduct['title'],$appid);


                    break;
                case "2": //余额支付
                    $paytype_table = "paytype";
                    $paytype_where['id'] = $paytype;
                    $pay_name = $common->public_select($paytype_table,$paytype_where)->value("name");
                    //查询账户余额是否充足
                    $admin_fans = "admin_fans";
                    $admin_fans_where['id'] = $userid;
                    $balance = $common->public_select($admin_fans,$admin_fans_where)->value("balance");
                    if($orderDetail['total_amount']>$balance){
                        throw new Exception("账户余额不足");
                    }
                    $common->public_select($admin_fans,$admin_fans_where)->setDec("balance",$orderDetail['total_amount']);
                    //记录余额明细
                    $log['fans_id'] = $userid;
                    $log['remark'] = "用户购买商品消费余额";
                    $log['type'] = "balance";
                    $log['type_status'] = 2;
                    $log['number'] = $orderDetail['total_amount'];
                    $log['before_number'] = $balance;
                    $log['after_number'] = $balance-$orderDetail['total_amount'];
                    $log['operator_id'] = $userid;
                    $common->createlog($log);
                    //生成订单操作流程
                    $ordeLog['order_id'] = $order_id;
                    $ordeLog['title'] = "订单已支付 支付方式：".$pay_name;
                    $ordeLog['remark'] = "支付成功，付款时间：".date("Y-m-d H:i:s",$pay_time);
                    $ordeLog['addtime'] = time();
                    $ordeLog['add_id'] = $userid;
                    $system_order_log = "tickets_order_log";
                    $common->handle($system_order_log,$ordeLog);
                    $realName = empty($fans['realName'])?$fans['nickname']:$fans['realName'];
                    $log['remark'] = "市民【" . $realName  . "】进行付款操作，核销码【".$orderDetail['order_sn']."】,关联id【".$order_id."】" ;
                    $common->addLog($log);
                    $data['status'] = 2;
                    $data['pay_type'] = $paytype;
                    $data['is_pay'] = 2;
                    $data['pay_time'] = $pay_time;
                    $data['id'] = $order_id;
                    $common->handle($tickets_order,$data);

                    //短信通知
                    $this->sms($orderDetail['order_sn'],$orderDetail['mobile']);

                    break;
                default:
            }
            $black['code'] = 0;
            $black['msg'] = "操作成功";
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }


    //更新订单状态
    public function updateStatus(){
        Db::startTrans();
        try{
            $common = new Common();
            $userid = $common->common();


            $whereFans['id'] = $userid;
            $fansTable = "admin_fans";
            $fans = $common->public_select($fansTable,$whereFans)->find();

            $realName = empty($fans['realName'])?$fans['nickname']:$fans['realName'];

            if(empty($_POST['order_id']) | empty($_POST['status'])){
                throw new Exception("非法操作");
            }
            $order_id = $_POST['order_id'];
            $status = $_POST['status'];

            //获取订单详情
            $tickets_order = "tickets_order";
            $tickets_order_where['id'] = $order_id;
            $orderDetail = $common->public_select($tickets_order,$tickets_order_where)->find();
            if(empty($orderDetail)){
                throw new Exception("订单信息不存在");
            }

            switch ($status){
                case 6:

                    if($status>2){
                        throw new Exception("当前订单不可以进行取消操作");
                    }

                    if($orderDetail['pay_type']==2){
                        //查询用户余额
                        $balance = $common->public_select($fansTable,$whereFans)->value("balance");
                        $common->public_select($fansTable,$whereFans)->setInc('balance',$orderDetail['real_pay']);
                        $log['fans_id'] = $orderDetail['fans_id'];
                        $log['remark'] = "用户取消订单退款入账";
                        $log['type'] = "balance";
                        $log['type_status'] = 1;
                        $log['number'] = $orderDetail['real_pay'];
                        $log['before_number'] = $balance;
                        $log['after_number'] = $balance+$orderDetail['real_pay'];
                        $log['operator_id'] = $orderDetail['fans_id'];
                        $log['order_sn'] = $orderDetail['order_sn'];
                        $common->createlog($log);
                    }
                    if(empty($_POST['cancel_remark'])){
                        throw new Exception("请完善取消原因等信息");
                    }
                    //生成订单操作流程
                    $ordeLog['order_id'] = $orderDetail['id'];
                    $ordeLog['title'] = "顾客取消订单 操作人：下单顾客";
                    $ordeLog['remark'] = $_POST['cancel_remark'];
                    $ordeLog['addtime'] = time();
                    $ordeLog['add_id'] = $userid;
                    $system_order_log = "tickets_order_log";
                    $common->handle($system_order_log,$ordeLog);
                    $data['cancel_reason'] = 'user';
                    $data['cancel_remark'] = $_POST['cancel_remark'];
                    break;
            }

            $data['status'] = $status;
            $common->public_select($tickets_order,$tickets_order_where)->update($data);

            $black['code'] = 0;
            $black['msg'] = "操作成功";
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    /**
     * 获取我的订单列表
     * @return false|string
     * @author zhixuedong
     * @date 2021/1/21/021
     */
    public function myOrder(){
        try{
            $common = new Common();
            $userid = $common->common();

            $page = empty($_POST['page']) ? 1 : $_POST['page'];
            $limit = empty($_POST['limit']) ? 10 : $_POST['limit'];
            $start = ($page - 1) * $limit;
            $where['a.fans_id'] = $userid;
            if(!empty($_POST['status'])){
                if($_POST['status']==4){
                    $where['a.status'] = 3;
                    $where['a.evaluation_status'] = 1;
                }else{
                    $where['a.status'] = $_POST['status'];
                }
            }
            $status_name = Config::get("Order_app_status");
            $is_pay = [1=>"未付款",2=>"已支付"];
            $list = Db::name("tickets_order")->alias("a")
                ->join("tickets_order_detail b","a.id=b.order_id")
                ->field("a.id,a.status,a.order_sn,a.total_amount,a.is_pay,b.title,b.count,b.thumb,a.addtime")
                ->where($where)->order("a.id desc")->select();
            foreach ($list as $k=>$v){
                $list[$k]['status'] = $status_name[$v['status']];
                $list[$k]['is_pay'] = $is_pay[$v['is_pay']];
                $list[$k]['addtime'] = date("Y-m-d H:i:s",$v['addtime']);
            }
            $black['code'] = 0;
            $black['list'] = $list;
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    /**
     * 我的订单详细信息
     * @author zhixuedong
     * @date 2021/1/27/027
     */
    public function orderDetail(){
        try{
            $where['a.id'] = $_POST['id'];
            $data = Db::name("tickets_order")->alias("a")
                ->join("tickets_order_detail b","a.id=b.order_id")
                ->field("a.id,a.status,a.order_sn,a.total_amount,b.title,b.count,b.thumb,b.effective_time,b.end_time,b.time_range,b.address,a.name,a.mobile,a.IDcard,a.remark,a.addtime")
                ->where($where)->find();
            $data['addtime'] = date("Y-m-d H:i:s",$data['addtime']);
            $black['code'] = 0;
            $black['data'] = $data;
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }


    /**
     * 模拟发放电子卡
     * @throws Exception
     * @throws \think\exception\PDOException
     * @author zhixuedong
     * @date 2021/1/31/031
     */
    public function notify(){

        //更新订单支付状态
        $where['order_sn'] = $_POST['order_sn'];//$result['out_trade_no']
        //$data['out_trade_order_id'] = $result['transaction_id'];
        $data['is_pay'] = 2;
        $data['status'] = 2;
        Db::name("tickets_order")->where($where)->update($data);

        $where['order_sn'] = $_POST['order_sn']; //$result['out_trade_no']
        $order = Db::name("tickets_order")->where($where)->find();
        //查询订单详情
        $detail = Db::name("tickets_order_detail")->where(['order_id'=>$order['id']])->find();
        //查询电子票批次
        $hairpin = Db::name("tickets_hairpin")->where(['type'=>2,'status'=>1])->order("id desc")->find();
        for ($i=1;$i<=$detail['count'];$i++){
            //生成电子票
            $no = $hairpin['sina'].date("Ymd");
            $token = $this->createtoken();
            $token = substr($token, 0,6);
            $no = $no.$token;
            $showmd5 = md5($no);
            $showmd5 = substr($showmd5, 0,6);
            $no = $no.$showmd5;
            $data['uniacid'] = $order['uniacid'];
            $data['hairpin_id'] = $hairpin['id'];
            $data['no'] = $no;
            $data['status'] = $hairpin['status'];
            $data['addtime'] = time();
            $data['order_id'] = $order['id'];
            $data['effectivetime'] = $detail['effective_time'];
            Db::name("tickets_card")->insertGetId($data,true);
            //绑定电子票
            $listData['order_id'] = $order['id'];
            $listData['tickets_id'] = $detail['tickets_id'];
            $listData['effective_time'] = $detail['effective_time'];
            $listData['end_time'] = $detail['end_time'];
            $listData['type'] = $detail['type'];
            $listData['signcode'] = $no;
            $listData['status'] = 1;
            $listData['addtime'] = time();
            $listData['degree'] = $detail['degree'];
            $listData['fans_id'] = $order['fans_id'];
            Db::name("tickets_list")->insertGetId($listData,true);
        }
    }


    /**
     * 生成加密算法
     * @return mixed
     * @author zhixuedong
     * @date 2021/1/29/029
     */
    public function createtoken(){
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < 32; $i++){
            $str .= $chars[mt_rand(0, $lc)].rand(1000000, 9999999);
        }
        return $str;
    }


}